<?php

namespace app\admin\controller;

use app\common\business\SysOperLog as SysOperLogBus;
use app\common\lib\toCamelCase;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SysOperLog extends AuthBase
{
    //获取操作日志列表查询条件
    public function operLogListSearch(){
        $where = [];
        // 获取分页参数
        $page = $this->request->get('pageNum', 1);
        $limit = $this->request->get('pageSize', 10);
        $operIp = $this->request->get('operIp',"");
        $title = $this->request->get('title',"");
        $operName = $this->request->get("operName","");
        $businessType = $this->request->get("businessType","");
        $status = $this->request->get("status","");
        $params = $this->request->get('params',"");
        if($operIp){
            $where[] = ['oper_ip', 'like', '%'.$operIp.'%'];
        }
        if($title){
            $where[] = ['title', 'like', '%'.$title.'%'];
        }
        if ($operName) {
            $where[] = ['oper_name', 'like', '%'.$operName.'%'];
        }
        if ($businessType) {
            $where[] = ['business_type', '=', $businessType];
        }
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["status", "=", $status];
        }
        if($params){
            $where[] = ['oper_time',">=",$params['beginTime']." 00:00:00"];
            $where[] = ['oper_time',"<=",$params['endTime']." 23:59:59"];
        }
        $where[] = ['del_flag','=','0'];
        $data = [
            'page'=>$page,
            'limit'=>$limit,
            'where'=>$where
        ];
        return $data;
    }

    //操作日志
    public function operLogList(){
        try {
            $searchData = $this->operLogListSearch();
            $orderByColumn = $this->request->get("orderByColumn","");
            $isAsc = $this->request->get("isAsc","");
            $order = [];
            if($orderByColumn && $isAsc){
                $isAsc = $isAsc === "ascending" ? 'asc': 'desc';
                $order = [
                    (new toCamelCase())->camelToSnake($orderByColumn) => $isAsc,
                ];
            }
            $OperLogData = (new SysOperLogBus())->getNormalOperLog($searchData['where'],'*',$searchData['limit'],$searchData['page'],$order);
            $OperLogData = (new toCamelCase())->toCamelCaseArray($OperLogData);
        }catch (\Exception $e){
            $OperLogData = [];
        }
        return show(config("status.success"),"操作日志列表",$OperLogData);
    }

    //删除操作日志
    public function operLogDel(){
        $operlog = $this->request->param("operlog","","trim");
        if(empty($operlog)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SysOperLogBus())->DelOperLogIds($operlog);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //清空操作日志
    public function operlogClean(){
        try {
            $result = (new SysOperLogBus())->operlogCleanBus();
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"操作成功",$result);
    }

    //导出操作日志
    public function operlogExport(){
        $searchData = $this->operLogListSearch();
        $orderByColumn = $this->request->get("orderByColumn","");
        $isAsc = $this->request->get("isAsc","");
        $order = [];
        if($orderByColumn && $isAsc){
            $isAsc = $isAsc === "ascending" ? 'asc': 'desc';
            $order = [
                (new toCamelCase())->camelToSnake($orderByColumn) => $isAsc,
            ];
        }
        $OperLogData = (new SysOperLogBus())->getNormalOperLog($searchData['where'],'*',$searchData['limit'],$searchData['page'],$order);
        // 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->mergeCells('A1:H1');
        $sheet->setCellValue('A1', '操作日志数据');
        // 设置表头
        $header = ['日志编号', '系统模块', '操作类型', '操作人员', '操作地址','操作地点','操作状态','操作日期','消耗时间'];
        $row = 2;
        $col = 1; // 列索引，从A列开始
        foreach ($header as $column) {
            // 使用setCellValueByColumnAndRow时，第二个参数是列号（整数），第三个参数是值
            $sheet->setCellValueByColumnAndRow($col, $row, $column);
            $col++; // 移动到下一列
        }
        // 使用循环设置列宽
        $columns = ['A', 'B', 'C', 'D', 'E', 'F','G','H','I']; // 定义需要设置宽度的列
        foreach ($columns as $column) {
            $sheet->getColumnDimension($column)->setWidth(18);
        }
        // 获取系统操作类型数据
        $sysOperTypeDta = (new \app\common\business\SysDictData())->getDictData('sys_oper_type');
        // 使用 array_column 简化数据映射
        $operTypeMap = array_column($sysOperTypeDta, 'dict_label', 'dict_value');
        $row = 3;
        // 填充数据
        foreach ($OperLogData['data'] as $post) {
            $business_type = $operTypeMap[$post['business_type']] ?? '其他';
            $post['status'] = $post['status'] === 0 ? "正常" : "异常";
            $sheet->setCellValue('A' . $row, $post['oper_id']);
            $sheet->setCellValue('B' . $row, $post['title']);
            $sheet->setCellValue('C' . $row, $business_type);
            $sheet->setCellValue('D' . $row, $post['oper_name']);
            $sheet->setCellValue('E' . $row, $post['oper_ip']);
            $sheet->setCellValue('F' . $row, $post['oper_location']);
            $sheet->setCellValue('G' . $row, $post['status']);
            $sheet->setCellValue('H' . $row, $post['oper_time']);
            $sheet->setCellValue('I' . $row, $post['cost_time']."毫秒");
            // 填充其他字段
            $row++;
        }
        $row = $row-1;
        $SpreadsheetObj = new \app\common\lib\Spreadsheet();
        $sheet->getStyle('A1')->applyFromArray($SpreadsheetObj->fontArray('FF000000',18));
        $sheet->getStyle('A2:I2')->applyFromArray($SpreadsheetObj->fillArray("808080"));
        $sheet->getStyle('A2:I2')->applyFromArray($SpreadsheetObj->fontArray("FFFFFFFF"));
        $sheet->getStyle('A1' . ':I' . $row)->applyFromArray($SpreadsheetObj->styleBorderArray());
        $sheet->getStyle('A1' . ':I' . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

        // 创建Writer对象，并保存为xlsx文件
        $writer = new Xlsx($spreadsheet);
        // 设置响应头
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="post.xlsx"');
        header('Cache-Control: max-age=0');
        // 导出
        $writer->save('php://output');
        exit;
    }
}
